﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;

namespace WP7DSMClient.Services.RunTime
{
    /// <summary>
    /// Provides runtime logging.
    /// </summary>
    public class LoggerService : WP7DSMClient.Services.ILoggerService
    {
        #region Private members

        //private static Logger _current = null;
        private const string FILENAME = "__logger.txt";

        #endregion

        #region Constructor

        /// <summary>
        /// Flush the log when starting.
        /// </summary>
        public LoggerService()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Clear the old log
                store.DeleteFile(FILENAME);
            }
        }

        #endregion

        //#region Public properties

        ///// <summary>
        ///// Exposes the logger instance. 
        ///// </summary>
        //public static Logger Current
        //{
        //    get 
        //    {
        //        if (_current == null)
        //        {
        //            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        //            {
        //                // Clear the old log
        //                store.DeleteFile(FILENAME);
        //            }
        //        }

        //        return _current; 
        //    }
        //}

        //#endregion

        #region ILogger implementation

        /// <summary>
        /// Logs a message.
        /// </summary>
        /// <param name="s">The message to log.</param>
        /// <param name="args">The parameters for the message.</param>
        public void SendLog(string s, params object[] args)
        {
            lock (this)
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                using (var stm = store.OpenFile(FILENAME, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
                {
                    // Move to the end
                    stm.Seek(0, SeekOrigin.End);

                    // Write the log
                    using (var writer = new StreamWriter(stm))
                    {
                        writer.WriteLine(s, args);
                    }
                }
            }
        }

        #endregion       
    }
}
